//
//  Timer.swift
//  DemoExtensionToday
//
//  Created by 唐可雄 on 16/5/13.
//  Copyright © 2016年 swustyc. All rights reserved.
//

import UIKit

// MARK: NSTimeInterval

extension NSTimeInterval {
    func toString() -> String {
        let totalSecond = Int(self)
        let minute = totalSecond / 60
        let second = totalSecond % 60
        
        switch (minute, second) {
        case (0...9, 0...9):
            return "0\(minute):0\(second)"
        case (0...9, _):
            return "0\(minute):\(second)"
        case (_, 0...9):
            return "\(minute):0\(second)"
        default:
            return "\(minute):\(second)"
        }
    }
}

// MARK: Timer

enum TimerErrType : Int {
    case AlreadyRunning = 1001
    case NegativeLeftTimer = 1002
    case NotRunning = 1003
}

class Timer: NSObject {
    
    // MARK: Setter and Getter
    
    ///
    var isRunning: Bool = false
    /// the int of leftTime
    var leftTime: NSTimeInterval {
        didSet {
            if leftTime < 0 {
                leftTime = 0
            }
        }
    }
    /// the description of leftTime
    var leftTimeStr: String {
        get {
            return leftTime.toString()
        }
    }
    
    // MARK: Object LifeCycle
    
    /// 倒计时过程处理
    private var timerTickHandler: (NSTimeInterval -> ())? = nil
    /// 倒计时结束处理
    private var timerStopHandler: (Bool ->())? = nil
    /// 倒计时
    private var timer: NSTimer!
    
    /// init
    init(timeInterval: NSTimeInterval) {
        leftTime = timeInterval;
    }
    
    /// start
    func start(prgressHandler: (NSTimeInterval -> Void)?, stopHandler: (Bool -> Void)?) -> (start: Bool, error: NSError?) {
        if isRunning {
            return (false, NSError(domain: "", code: TimerErrType.AlreadyRunning.rawValue, userInfo: nil))
        }
        if leftTime < 0 {
            return (false, NSError(domain: "", code: TimerErrType.NegativeLeftTimer.rawValue, userInfo: nil))
        }
        
        timerTickHandler = prgressHandler
        timerStopHandler = stopHandler
        
        isRunning = true
        
        timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: NSSelectorFromString("countTick"), userInfo: nil, repeats: true)
        
        return (true, nil)
    }
    
    /// stop
    func stop() -> (stopped: Bool, error: NSError?) {
        if !isRunning {
            return (false, NSError(domain: "", code: TimerErrType.NotRunning.rawValue, userInfo: nil))
        }
        
        isRunning = false
        
        timer.invalidate()
        timer = nil
        
        if let stopHandler = timerStopHandler {
            stopHandler(leftTime <= 0)
        }
        
        timerStopHandler = nil
        timerTickHandler = nil
        
        return (true, nil)
    }
    
    @objc private func countTick() {
        leftTime = leftTime - 1
        
        if let tickHandler = timerTickHandler {
            tickHandler(leftTime)
        }
        
        if leftTime <= 0 {
            stop()
        }
    }
}